package gazzera.node.core.plugins.shareplugin;

import gazzera.node.core.*;
import gazzera.node.core.messages.*;
import gazzera.node.core.plugins.shareplugin.db.*;
import gazzera.utils.*;

import java.io.*;
import java.util.*;


public class FileListPump implements DataPumpSource
{
	private String parent;
	private HashDatabase db;
	private boolean finishedSend = false;
	private Set<Share> visibleShares;
	private Iterator<File> iterator = null;
	private ShareList shares = null;

	public FileListPump(String parent, HashDatabase db, Set<Share> visibleShares, ShareList shares)
	{
		this.parent = parent;
		this.db = db;
		this.visibleShares = visibleShares;
		this.shares = shares;
	}
	@Override
	public void finished(boolean interrupted)
	{
		iterator = null;
	}

	@Override
	public void init()
	{
		List<File> filesToSend;
		if(parent.equals(""))
		{
		    // requested the root, let's send all shares he see
    			filesToSend = new ArrayList<File>();
    			for (Share s : visibleShares) 
    			{
    				filesToSend.add(s.getFolder());
    			}
		}
		else
		{
		    String prt = shares.sharedToLocalPath(parent);
			if (prt == null)
			{
				filesToSend = new ArrayList<File>();
			}
			else
			{
				File localParent = new File(prt);
				Share share = shares.findShared(localParent);
				if(visibleShares.contains(share))
				{
				    filesToSend = Arrays.asList( localParent.listFiles() );
				}
				else
				{
				    filesToSend = new ArrayList<File>();
				}
			}
			
		}
		
		iterator = filesToSend.iterator();
		
	}

	@Override
	public Message next() throws Exception
	{
		if(finishedSend)
		{
			return null;
		}
		
		if (!iterator.hasNext())
		{
			finishedSend = true;
			return new BrowseReplyFinished(parent);
		}
		
		File d = iterator.next();
		if(d.isDirectory())
		{
			return new BrowseReplyFolder(parent, d.getName(), true);
		}
		else
		{
			// here i only send the hash, not the fileid, as it can be calculated remotely
		    Hash hash = db.getHash(d, false);
		    
		    return new BrowseReplyFile(parent, hash, d.getName(), d.length(), d.lastModified());
		}
	}

}
